package com.k.activemq.openwire_sync1.listener;

import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import java.sql.SQLOutput;
import java.util.concurrent.TimeUnit;

public class CustomMessageListener extends AbstractMessageListener {
    private String requestId;
    private Long reqMills;
    private Long ttl;

    public CustomMessageListener(Session session, String requestId, Long reqMills, Long ttl) {
        super(session);
        this.requestId = requestId;
        this.reqMills = reqMills;
        this.ttl = ttl;
    }

    public CustomMessageListener(Session session) {
        super(session);
    }

    void onMessageDo(Session session, Message message) throws Exception {
        System.out.println("消费者接收到消息：" + message);
        // 如果 replay=null 则该消息未设置回应地址
        System.out.println("消费者接收：replay:" + message.getJMSReplyTo());
        System.out.println("消费者等待....");
        TimeUnit.SECONDS.sleep(10);
        System.out.println("消费者：创建producer");
        MessageProducer producer = session.createProducer(message.getJMSReplyTo());
        System.out.println("消费者:发送回执：");
        producer.send(session.createTextMessage("user=huizhi1639"));
        System.out.println("消消费者:发送回执：完毕");
    }

    void onMessageDo(Session session, Message message, String requestId, Long reqMills, Long ttl) {
        Long respMillis = System.currentTimeMillis();
        if (respMillis - reqMills > ttl) {
            throw new RuntimeException("请求超时 ttl:" + ttl);
        }
        System.out.println("消费者：接收："+message);
    }
    void onMessageDo(Message message){
        System.out.println("消费者：接收："+message);
    }

    @Override
    void onMessage(Session session, Message message) {
        try {
            if (requestId != null && ttl != null) {
                onMessageDo(session, message, requestId, reqMills, ttl);
            } else {
                onMessageDo(session, message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
